package com.dimbottom.entity.rest;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author DimBottom
 * @since 17:00  2020-08-31
 */
public class RestBody<T> implements Rest<T>, Serializable {

    private static final long serialVersionUID = -3336875324869755590L;
    private int code;
    private T data;
    private String msg;
    private List<String> errors;

    private RestBody() {
        this.code = Code.OK;
    }

    public RestBody(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(String... error) {
        if (errors == null)
            errors = new ArrayList<>();
        errors.addAll(Arrays.asList(error));
    }

    public static Rest<Void> ok() {
        return new RestBody<>();
    }

    public static Rest<Void> ok(String msg) {
        RestBody<Void> restBody = new RestBody<>();
        restBody.setMsg(msg);
        return restBody;
    }

    public static <T> Rest<T> okData(T data) {
        RestBody<T> restBody = new RestBody<>();
        restBody.setData(data);
        return restBody;
    }

    public static <T> Rest<T> okData(T data, String msg) {
        RestBody<T> restBody = new RestBody<>();
        restBody.setData(data);
        restBody.setMsg(msg);
        return restBody;
    }

    public static <T> Rest<T> build(int code, T data, String msg, String... errors) {
        RestBody<T> restBody = new RestBody<>(code);
        restBody.setData(data);
        restBody.setMsg(msg);
        restBody.setErrors(errors);
        return restBody;
    }


    public static Rest<Void> error(String... error) {
        return failure(400, error);
    }

    public static <T> Rest<T> errorData(int code, T data, String... error) {
        return failureData(code, data, error);
    }


    public static Rest<Void> failure(int code, String... error) {
        RestBody<Void> restBody = new RestBody<>(code);
        restBody.setErrors(error);
        return restBody;
    }

    public static <T> Rest<T> failureData(int code, T data, String... errors) {
        RestBody<T> restBody = new RestBody<>(code);
        restBody.setData(data);
        restBody.setErrors(errors);
        return restBody;
    }
}
